<?php
/**
 * MatchDart! is a darts event ranking table component for joomla
 *
 * @version		2.0.1 | $Id: match.php 108 2009-09-01 12:35:33Z mwi.nor $
 * @package		MatchDart!
 * @subpackage	Admin
 * @copyright	Copyright (C) 2005 - 2009 Marco Wilde. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * @author		Marco Wilde, <mailto://info@matchdart.de>
 * @link		http://www.matchdart.de
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

// Include the syndicate functions only once
require_once(  JPATH_COMPONENT.DS.'helpers'.DS.'helper.php' );
require_once(  JPATH_COMPONENT.DS.'models'.DS.'event.php' );


class MatchdartModelMatch extends JModel
{
	protected $_data = null;
	protected $_id = null;
	protected $_eventid = null;
	protected $_eventdata = null;
	protected $_eventselect = null;
	protected $_seasonselect = null;
	protected $_venueselect = null;
	protected $_homePlayerSelect = null;
	protected $_hometeamselect = null;
	protected $_awayPlayerSelect = null;
	protected $_awayteamselect = null;
	protected $_matchTypeSelect = null;

	public function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	}

	public function setId($id)
	{
		// Set id and wipe data
		$this->_id        = $id;
		$this->_data    = null;
	}


	/**
	 *  get the actual event id
	 *  if no event is selected use default event id from events table
	 *
	 */
	public function getEventID()
	{
		if (empty($this->_eventid))
		{
			// default event id
			$eventid	= modMatchDartHelper::getDefaultEventID();

			// actual match event id (if a match is selected)
			$matchdata 	= $this->getData();
			if (isset($matchdata->MatchEventID)) {
				$eventid = $matchdata->MatchEventID;
			}

			$this->_eventid = JRequest::getVar('SelectEventID',  $eventid, 'post', 'int');
		}
		return $this->_eventid;
	}

	/**
	 * get the actual event data from events table
	 *
	 */
	public function getEventData()
	{
		if (empty($this->_eventdata))
		{
			$id	= $this->getEventID();
			$event =& new MatchDartModelEvent;
			
			$event->setId($id);
			$this->_eventdata = $event->getData();

//			$query		= 'SELECT * FROM #__md_events '.
//	                 	  ' WHERE EventID = '.(int) $id;
//			$this->_db->setQuery( $query );
//			$this->_eventdata	= $this->_db->loadObject();
		}
		return $this->_eventdata;
	}

	public function getMatchTypeSelect()
	{
		if (empty($this->_matchTypeSelect))
		{
			$matchdata		= $this->getData();
			$currentValue	= isset($matchdata->MatchType) ? $matchdata->MatchType : $currentValue = 0;

			$option[1] = JHTML::_('select.option', '0', JText::_( 'MD_MATCH_TYPE_LEAGUE'));
			$option[2] = JHTML::_('select.option', '1', JText::_( 'MD_MATCH_TYPE_BEST_2'));
			$option[3] = JHTML::_('select.option', '2', JText::_( 'MD_MATCH_TYPE_BEST_4'));
			$option[4] = JHTML::_('select.option', '4', JText::_( 'MD_MATCH_TYPE_BEST_8'));
			$option[5] = JHTML::_('select.option', '8', JText::_( 'MD_MATCH_TYPE_BEST_16'));
			$option[6] = JHTML::_('select.option', '16', JText::_( 'MD_MATCH_TYPE_BEST_32'));

			$this->_matchTypeSelect = JHTML::_('select.genericlist', $option, 'SelectMatchType', null, 'value', 'text', $currentValue);
		}

		return $this->_matchTypeSelect;

	}


	public function getData()
	{
//		$app = &JFactory::getApplication();

		// Load the data
		if(empty( $this->_data )) {
			$query = ' SELECT * FROM #__md_matches '.
                 '  WHERE MatchID = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			$this->_data = $this->getTable('matches');
			$this->_data->id = 0;
		}
		return $this->_data;
	}

	public function store()
	{
			
		//get input from form
		$input['MatchID'] = JRequest::getVar('cid',  0, 'post', 'int');
		$input['MatchDate'] = JRequest::getVar('MatchDate',  0, 'post', 'string');
		$input['MatchEventID'] = JRequest::getVar('SelectEventID',  0, 'post', 'int');
		$input['MatchSeasonID'] = JRequest::getVar('SelectSeasonID',  0, 'post', 'int');
		$input['MatchVenueID'] = JRequest::getVar('SelectVenueID',  0, 'post', 'int');
		$input['MatchType'] = JRequest::getVar('SelectMatchType',  0, 'post', 'int');

		$input['MatchHomePlayerID'] = JRequest::getVar('MatchHomePlayerID',  0, 'post', 'int');
		$input['MatchHomeTeamID'] = JRequest::getVar('MatchHomeTeamID',  -1, 'post', 'int');
		$input['MatchHomeSets'] = JRequest::getVar('MatchHomeSets',  0, 'post', 'int');
		$input['MatchHomeLegs'] = JRequest::getVar('MatchHomeLegs',  0, 'post', 'int');
		$input['MatchHomeLWAT'] = JRequest::getVar('MatchHomeLWAT',  0, 'post', 'int');
		$input['MatchHomeBonus'] = JRequest::getVar('MatchHomeBonus',  0, 'post', 'int');
		$input['MatchHomeHC'] = JRequest::getVar('MatchHomeHC',  0, 'post', 'int');
		$input['MatchHome180'] = JRequest::getVar('MatchHome180',  0, 'post', 'int');
		$input['MatchHome140'] = JRequest::getVar('MatchHome140',  0, 'post', 'int');
		$input['MatchHome100'] = JRequest::getVar('MatchHome100',  0, 'post', 'int');
		$input['MatchHomeAVG3'] = JRequest::getVar('MatchHomeAVG3',  0, 'post', 'int');
		$input['MatchHomeAVG1'] = JRequest::getVar('MatchHomeAVG1',  0, 'post', 'int');

		$input['MatchAwayPlayerID'] = JRequest::getVar('MatchAwayPlayerID',  0, 'post', 'int');
		$input['MatchAwayTeamID'] = JRequest::getVar('MatchAwayTeamID',  -1, 'post', 'int');
		$input['MatchAwaySets'] = JRequest::getVar('MatchAwaySets',  0, 'post', 'int');
		$input['MatchAwayLegs'] = JRequest::getVar('MatchAwayLegs',  0, 'post', 'int');
		$input['MatchAwayLWAT'] = JRequest::getVar('MatchAwayLWAT',  0, 'post', 'int');
		$input['MatchAwayBonus'] = JRequest::getVar('MatchAwayBonus',  0, 'post', 'int');
		$input['MatchAwayHC'] = JRequest::getVar('MatchAwayHC',  0, 'post', 'int');
		$input['MatchAway180'] = JRequest::getVar('MatchAway180',  0, 'post', 'int');
		$input['MatchAway140'] = JRequest::getVar('MatchAway140',  0, 'post', 'int');
		$input['MatchAway100'] = JRequest::getVar('MatchAway100',  0, 'post', 'int');
		$input['MatchAwayAVG3'] = JRequest::getVar('MatchAwayAVG3',  0, 'post', 'int');
		$input['MatchAwayAVG1'] = JRequest::getVar('MatchAwayAVG1',  0, 'post', 'int');

		// update default values according to event settings
		$eventid = $input->MatchEventID;
		$event = $this->getEventData();

		if ($event->EventUseSets == 0) {
			$input['MatchHomeSets'] = -1;
			$input['MatchAwaySets'] = -1;
		}

		if ($event->EventUseXStats == 0) {
			$input['MatchHome140'] = -1;
			$input['MatchHome100'] = -1;
			$input['MatchHomeAVG3'] = -1;
			$input['MatchHomeAVG1'] = -1;

			$input['MatchAway140'] = -1;
			$input['MatchAway100'] = -1;
			$input['MatchAwayAVG3'] = -1;
			$input['MatchAwayAVG1'] = -1;
		}

		// calculate match result and additional match data
		$data = $this->getMatchResult($input);

		$data['MatchCreated'] = time();
		$data['MatchUseXStats'] = $event->EventUseXStats;

		// get the matches table
		$row =& $this->getTable('matches');

		// Bind the form fields to the hello table
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Make sure the hello record is valid
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Store the entry to the database
		if (!$row->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;

		}
		return true;
	}

	public function delete()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
		$row =& $this->getTable('matches');

		foreach($cids as $cid) {
			if (!$row->delete( $cid )) {
				$this->setError( $row->_db->getErrorMsg() );
				return false;
			}
		}

		return true;
	}

	/**
	 * get a selection of published events from events table
	 * and render a select box - preselect the actual event
	 *
	 */
	public function getEventSelect()
	{

		$currentValue = $this->getEventID();
			
		if (empty($this->_eventselect))
		{
			$query = 'SELECT * FROM #__md_events WHERE EventPublish = 1 ORDER BY EventID';
			$events = $this->_getList($query);
			$k=1;

			//FIXME: 'foreach' --> error if events table empty
			foreach ($events as $event){
				$option[$k] = JHTML::_('select.option', $event->EventID, $event->EventName);
				$k++;
			}

			$this->_eventselect = JHTML::_('select.genericlist', $option, 'SelectEventID', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $currentValue);

		}
		return $this->_eventselect;
	}

	public function getSeasonSelect()
	{
		$matchdata 	= $this->getData();
		$d_seasonid = modMatchDartHelper::getDefaultSeasonID();

		$seasonid 	= ($matchdata->MatchSeasonID <> 0 ) ? $matchdata->MatchSeasonID : $d_seasonid;
			
		if (empty($this->_seasonselect))
		{
			$query = 'SELECT * FROM #__md_seasons ORDER BY SeasonID';
			$seasons = $this->_getList($query);

			$k=1;
			//FIXME: 'foreach' --> error if seasons table empty
			foreach ($seasons as $season){
				$inactive = ($season->SeasonPublish == 0) ? 'true' : 'false';
				$option[$k] = JHTML::_('select.option', $season->SeasonID, $season->SeasonName);
				$k++;
			}

			$this->_seasonselect = JHTML::_('select.genericlist', $option, 'SelectSeasonID', null, 'value', 'text', $seasonid);

		}
		return $this->_seasonselect;
	}

	public function getVenueSelect()
	{
		$matchdata = $this->getData();
			
		if (empty($this->_venueselect))
		{
			$currentValue = $matchdata->MatchVenueID;
			$query = 'SELECT * FROM #__md_venues ORDER BY VenueName';
			$venues = $this->_getList($query);

			$k=1;
			//FIXME: 'foreach' --> error if events table empty
			$option[0] = JHTML::_('select.option', '0', JText::_( 'MD_SELECT_NONE'));
			foreach ($venues as $venue){
				$option[$k] = JHTML::_('select.option', $venue->VenueID, $venue->VenueName);
				$k++;
			}

			$this->_venueselect = JHTML::_('select.genericlist', $option, 'SelectVenueID', null, 'value', 'text', $currentValue);

		}
		return $this->_venueselect;
	}
	
	/**
	 * Get a player / team select list
	 *
	 * Returns a select box with player/team names depending on 
	 * event player / team list and team player list
	 *
	 * @access	protected
	 * @param	string	$type 			'homeplayer', 'awayplayer', 'hometeam', 'awayteam'
	 * @param	int		$currentValue	value to preselect
	 * @param	bool	$reload			reload form on select
	 * 
	 * @return object JHTML 
	 */
	
	protected function _getOpponentSelect($type, $reload = false, $currentValue = 0)
	{
		$auto			= ($reload) ? 'class="inputbox" size="1" onchange="document.adminForm.submit( );"' : null;
		$matchdata		= $this->getData();
		
		switch ( $type )
		{
			case 'homeplayer'  :	
			$currentValue	= $matchdata->MatchHomePlayerID;
			$selTeam 		= JRequest::getVar('MatchHomeTeamID',  0, 'post', 'int');
			$varName		= 'MatchHomePlayerID';
			$opponentID		= 'PlayerID';
			$table			= '#__md_players';
			$opponentName	= 'PlayerName';
			break;
			case 'awayplayer'  :	
			$currentValue	= $matchdata->MatchAwayPlayerID;
			$selTeam 		= JRequest::getVar('MatchAwayTeamID',  0, 'post', 'int');
			$varName		= 'MatchAwayPlayerID';
			$opponentID		= 'PlayerID';
			$table			= '#__md_players';
			$opponentName	= 'PlayerName';
			break;
			case 'hometeam'  :	
			$currentValue	= ($matchdata->MatchHomeTeamID) ? $matchdata->MatchHomeTeamID : JRequest::getVar('MatchHomeTeamID',  0, 'post', 'int');
			$varName		= 'MatchHomeTeamID';
			$opponentID		= 'TeamID';
			$table			= '#__md_teams';
			$opponentName	= 'TeamName';
			break;
			case 'awayteam'  :	
			$currentValue	= ($matchdata->MatchAwayTeamID) ? $matchdata->MatchAwayTeamID : JRequest::getVar('MatchAwayTeamID',  0, 'post', 'int');
			$varName		= 'MatchAwayTeamID';
			$opponentID		= 'TeamID';
			$table			= '#__md_teams';
			$opponentName	= 'TeamName';
			break;
		}
		
		//get the event player / team list for selection
		$eventData = $this->getEventData();
		$eventOpponents = ($type == 'homeplayer' OR $type == 'awayplayer') ? $eventData->EventPlayers : $eventData->EventTeams;
		
		//for team event get the players associated to each team
		if ($selTeam != 0)
		{
            $query = ' SELECT * FROM #__md_teams '.
                 '  WHERE TeamID = '.$selTeam;
            $this->_db->setQuery( $query );
            $teamdata = $this->_db->loadObject();
			//$teamplayers = $teamdata->TeamPlayers;
			
			$eventOpponents = $teamdata->TeamPlayers;
		}
		  

		//attach current player / team if not in list
		if (($currentValue > 0) AND !in_array($currentValue, explode(',',$eventOpponents))) {
			$eventOpponents = ($eventOpponents == '-1') ? $currentValue : $eventOpponents.','.$currentValue;
		}
				
		//build the WHERE clause
		$where = ($eventOpponents == '-1') ? '' : 'WHERE '.$opponentID.' in ('.$eventOpponents.')';

		//get the opponent data from the table where the opponent is in the list
		$query = 'SELECT '.$opponentID.' AS OpponentID, '.$opponentName.' AS OpponentName FROM '.$table.' '.$where.' ORDER BY '.$opponentName;
		$opponents = $this->_getList($query);

		//set the options for the select box
		$option[0] = JHTML::_('select.option', '0', JText::_( 'MD_SELECT_NONE'));
		$k=1;
		if (count($opponents) > 0)
			{
				foreach ($opponents as $opponent){
					$option[$k] = JHTML::_('select.option', $opponent->OpponentID, $opponent->OpponentName);
					$k++;
				}
					
			}
		$opponentSelect = JHTML::_('select.genericlist', $option, $varName, $auto, 'value', 'text', $currentValue);

		return $opponentSelect;
	}


	public function getHomePlayerSelect()
	{
		if (empty($this->_homePlayerSelect)) {
			$this->_homePlayerSelect = $this->_getOpponentSelect('homeplayer');
		}
		return $this->_homePlayerSelect;
	}

	public function getAwayPlayerSelect()
	{
		if (empty($this->_awayPlayerSelect)) {
			$this->_awayPlayerSelect = $this->_getOpponentSelect('awayplayer');
		}
		return $this->_awayPlayerSelect;
	}

	public function getHomeTeamSelect()
	{
		if (empty($this->_homeTeamSelect)) {
			$this->_homeTeamSelect = $this->_getOpponentSelect('hometeam',true);
		}
		return $this->_homeTeamSelect;
			}

	public function getAwayTeamSelect()
	{
		if (empty($this->_awayTeamSelect)) {
			$this->_awayTeamSelect = $this->_getOpponentSelect('awayteam',true);
		}
		return $this->_awayTeamSelect;
			}

	public function getMatchCalendar()
	{
		$matchdata = $this->getData();
		$date = $matchdata->MatchDate;
			
		$value = ($date == 0) ? date('Y-m-d',time()) : $date;
		$name = 'MatchDate';
		$id = 'matchdate';
		$format = '%Y-%m-%d';

		$calendar =  JHTML::calendar($value, $name, $id, $format);

		return $calendar;

	}

	public function getMatchResult($match)
	{
		$eventid = $match['MatchEventID'];
			
		$event = $this->getEventData();
			
			
		if ($event->EventUseSets == 1)
		{
			if ($match['MatchHomeSets'] > $match['MatchAwaySets'])
			{
				$match['MatchResult'] = 1;
			}
			if ($match['MatchHomeSets'] < $match['MatchAwaySets'])
			{
				$match['MatchResult'] = 2;
			}
			if ($match['MatchHomeSets'] == $match['MatchAwaySets'])
			{
				$match['MatchResult'] = 0;
			}

		} else {
			if ($match['MatchHomeLegs'] > $match['MatchAwayLegs'])
			{
				$match['MatchResult'] = 1;
			}
			if ($match['MatchHomeLegs'] < $match['MatchAwayLegs'])
			{
				$match['MatchResult'] = 2;
			}
			if ($match['MatchHomeLegs'] == $match['MatchAwayLegs'])
			{
				$match['MatchResult'] = 0;
			}

		}
			
		return $match;
			
	}

}
?>